package me.mononin.factory.data.user;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import me.mononin.factory.data.helper.DbHelper;
import me.mononin.factory.model.card.UserCard;
import me.mononin.factory.model.db.User;

public class UserDispatcher implements UserCenter{
    //单例
    public static UserDispatcher instance;
    //单线程池
    private final Executor executor = Executors.newSingleThreadExecutor();

    public static UserDispatcher instance(){
        if (instance==null){
            synchronized (UserDispatcher.class){
                if (instance==null){
                    instance = new UserDispatcher();
                }
            }
        }
        return instance;
    }

    @Override
    public void dispatch(UserCard... userCards) {
        if (userCards==null||userCards.length==0){
            return;
        }

        executor.execute(new UserCardHandler(userCards));
    }

    private class UserCardHandler implements Runnable{
        private final UserCard[] cards;

        UserCardHandler(UserCard... userCards){
            this.cards = userCards;
        }
        @Override
        public void run() {
            //单线程调度时触发
            List<User> users = new ArrayList<>();
            //遍历
            for (UserCard card : cards){
                if (card==null|| TextUtils.isEmpty(card.getId())){
                    //进行过滤
                    continue;
                }
                //执行添加操作
                users.add(card.build());
            }
            //添加数据存储，并分发通知，异步操作
            DbHelper.save(User.class,users.toArray(new User[0]));
        }
    }
}
